import React, { useEffect, useState } from "react";
import axios from "axios";
import { Notify, Image } from "react-vant";
import { List } from "react-vant";
import { useNavigate } from "react-router-dom";

export interface ListItemType {
  title: string;
  url: string;
  desc: string;
  id: string;
}

export const Recommend = () => {
  const [pageCode, setPageCode] = useState(1);
  const [list, setList] = useState<ListItemType[]>([]);
  const [finished, setFinished] = useState(false);
  const navigate = useNavigate();
  const fetchList = async () => {
    const resp = await axios.get("/api/list", { params: { pageCode } });
    const { code, message, data } = resp.data;
    if (code === 200) {
      setList(list.concat(data));
      Notify({ type: "success", message });
    } else {
      Notify({ type: "danger", message });
      setFinished(true);
    }
  };

  useEffect(() => {
    fetchList();
  }, [pageCode]);

  if (list.length === 0) {
    return <div>数据拼命加载中...</div>;
  }

  return (
    <div className="list">
      <List
        finished={finished}
        onLoad={async () => setPageCode(pageCode + 1)}
        finishedText="没有更多数据了"
      >
        {list.map((v) => {
          return (
            <dl
              key={v.id}
              className="list-item"
              onClick={() =>
                navigate("/detail/" + v.id, {
                  state: v,
                })
              }
            >
              <dt>
                <Image src={v.url} alt="" width={120} height={80} lazyload />
              </dt>
              <dd>
                <h3>{v.title}</h3>
                <p>{v.desc}</p>
              </dd>
            </dl>
          );
        })}
      </List>
    </div>
  );
};
